﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;

namespace CMS.Common
{
    /// <summary>
    /// Author:		 喻旻
    /// Create date: 2011-07-11
    /// Description: 公共工具类
    /// </summary>
    public class CommTools
    {
        ///   <summary> 
        ///   Resize图片 
        ///   </summary> 
        ///   <param   name= "bmp "> 原始Bitmap </param> 
        ///   <param   name= "newW "> 新的宽度 </param> 
        ///   <param   name= "newH "> 新的高度 </param> 
        ///   <returns> 处理以后的Bitmap </returns> 
        public static byte[] KiResizeImage(Bitmap bmp, int newW, int newH)
        {
            try
            {

                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();
                EncoderParameters eps = new EncoderParameters(1);
                EncoderParameter ep = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);//质量等级90%  
                eps.Param[0] = ep;
                byte[] data = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    b.Save(ms, ImageFormat.Jpeg);
                    data = ms.ToArray();
                }
                return data;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="data">文件字节数组</param>
        /// <param name="filePath">文件路径</param>
        public static void SaveFile(byte[] data, string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            if (!file.Directory.Exists)
            {
                file.Directory.Create();
            }
            File.WriteAllBytes(filePath, data);
        }
    }
}
